import 'package:cached_network_image/cached_network_image.dart';
import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../common/constants.dart';
import '../controllers/comment_input_controller.dart';

class CommentInputPage extends StatelessWidget {
  CommentInputPage({super.key});

  final CommentInputController controller = Get.find<CommentInputController>();

  _buildEmojiPanel() {
    return SizedBox(
      width: double.infinity,
      height: 285,
      child: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Divider(
                color: Colors.black12,
                height: 1,
              ),
              _buildEmotionTypeList(),
              _buildEmotionListView()
            ],
          ),
          if (controller.selectedIndex.value == 0)
            Positioned(
              right: 10,
              bottom: 20,
              child: GestureDetector(
                child: Container(
                  decoration: BoxDecoration(
                    color: Color(0xFF252525),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  padding: EdgeInsets.symmetric(horizontal: 15, vertical: 6),
                  child: Icon(
                    Icons.backspace_outlined,
                    color: Colors.white,
                    size: 24,
                  ),
                ),
                onTap: () {
                  controller.deleteText();
                },
              ),
            )
        ],
      ),
    );
  }

  _buildEmotionListView() {
    if (controller.selectedIndex.value == 0) {
      return Expanded(
        child: GridView.builder(
          physics: const BouncingScrollPhysics(),
          padding: const EdgeInsets.all(10),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 7,
          ),
          itemCount: controller.emojiMap.length,
          itemBuilder: (context, index) {
            final v = controller.emojiMap.values.toList();
            return GestureDetector(
              behavior: HitTestBehavior.translucent,
              child: Column(
                children: [
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                    child: Image.asset(
                      v[index],
                      fit: BoxFit.contain,
                    ),
                  )
                ],
              ),
              onTap: () {
                List<dynamic> keys = controller.emojiMap.keys.toList();
                String k = keys[index];
                controller.addEmoji(k);
              },
            );
          },
        ),
      );
    } else {
      final emotion = controller.emotionList[controller.selectedIndex.value];
      final count = emotion.items.length;
      return Expanded(
        child: CustomScrollView(
          physics: const BouncingScrollPhysics(),
          slivers: [
            SliverToBoxAdapter(
              child: Container(
                padding: EdgeInsets.all(10),
                color: Colors.transparent,
                child: Text(
                  controller.emotionList[controller.selectedIndex.value].category,
                  style: TextStyle(color: Colors.grey),
                ),
              ),
            ),
            // GridView 部分
            SliverGrid(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4,
                childAspectRatio: (Get.width / 4) / 120,
                mainAxisSpacing: 10,
                crossAxisSpacing: 10,
              ),
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  final item = emotion.items[index];
                  return GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 4),
                          child: CachedNetworkImage(
                            imageUrl: "https://img.ideaflow.pro/emoji/${item.url}",
                            fit: BoxFit.contain,
                          ),
                        ),
                        Text(
                          item.name,
                          style: TextStyle(color: Colors.white54),
                        )
                      ],
                    ),
                    onTap: () {
                      controller.selectedEmotion.value = "https://img.ideaflow.pro/emoji/${item.url}";
                    },
                  );
                },
                childCount: count, // GridView 的项数
              ),
            ),
          ],
        ),
      );
    }
  }

  _buildEmotionTypeList() {
    return SizedBox(
      width: double.infinity,
      height: 40,
      child: ListView.builder(
        physics: const BouncingScrollPhysics(),
        scrollDirection: Axis.horizontal,
        itemCount: controller.emotionList.length,
        itemBuilder: (BuildContext context, int index) {
          final data = controller.emotionList[index];
          return GestureDetector(
            child: Container(
              decoration: BoxDecoration(
                color: controller.selectedIndex.value == index ? Colors.white12 : Colors.transparent,
                borderRadius: BorderRadius.circular(20),
              ),
              padding: EdgeInsets.symmetric(horizontal: 13, vertical: 6),
              margin: EdgeInsets.only(left: 4, top: 0),
              child: CachedNetworkImage(
                imageUrl: data.icon,
                width: 28,
                height: 28,
                fit: BoxFit.cover,
              ),
            ),
            onTap: () {
              controller.selectedIndex.value = index;
            },
          );
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    controller.keyboardHeight = MediaQuery.of(context).viewInsets.bottom;
    //print("keyboardHeight=${controller.keyboardHeight}");
    return Scaffold(
      backgroundColor: Colors.black26,
      resizeToAvoidBottomInset: false,
      body: Column(children: [
        Expanded(
          child: GestureDetector(
            child: Container(color: Colors.transparent),
            onTap: () {
              Get.back();
            },
          ),
        ),
        Obx(() {
          return Container(
            color: Color(0xFF1A1A1A),
            child: Column(
              children: [
                Container(
                  width: double.infinity,
                  margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                  decoration: BoxDecoration(
                    color: Color(0xFF242424),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      ExtendedTextField(
                        keyboardType: TextInputType.multiline,
                        maxLines: null,
                        showCursor: true,
                        focusNode: controller.focusNode,
                        cursorColor: Colors.white,
                        strutStyle: const StrutStyle(),
                        specialTextSpanBuilder: controller.mySpecialTextSpanBuilder,
                        controller: controller.textEditingController,
                        style: TextStyle(color: Colors.white),
                        decoration: InputDecoration(
                          enabledBorder: UnderlineInputBorder(
                            borderSide: BorderSide.none,
                          ),
                          focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide.none,
                          ),
                          contentPadding: EdgeInsets.symmetric(horizontal: 10),
                          hintText: "发评论...",
                          hintStyle: TextStyle(fontSize: 14, color: Colors.white54),
                        ),
                      ),
                      if (controller.selectedEmotion.value.isNotEmpty)
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                          child: Stack(
                            children: [
                              ClipRRect(
                                borderRadius: BorderRadius.circular(10),
                                child: CachedNetworkImage(
                                  imageUrl: controller.selectedEmotion.value,
                                  width: 60,
                                  height: 60,
                                  fit: BoxFit.cover,
                                ),
                              ),
                              Positioned(
                                right: 1,
                                top: 1,
                                child: GestureDetector(
                                  child: Container(
                                    padding: EdgeInsets.all(3),
                                    decoration: BoxDecoration(
                                      color: Colors.black38,
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    child: Icon(
                                      CupertinoIcons.clear,
                                      size: 13,
                                      color: Colors.white,
                                    ),
                                  ),
                                  onTap: () {
                                    controller.selectedEmotion.value = "";
                                  },
                                ),
                              ),
                            ],
                          ),
                        ),
                    ],
                  ),
                ),
                Row(
                  children: [
                    InkWell(
                      child: Container(
                        padding: EdgeInsets.only(left: 15, top: 5, bottom: 10),
                        child: Icon(
                          Icons.image,
                          color: Colors.white,
                          size: 20,
                        ),
                      ),
                      onTap: () {},
                    ),
                    GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      child: Container(
                        padding: EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 10),
                        child: Icon(
                          controller.showEmojiPanel.value ? Icons.emoji_emotions_outlined : Icons.keyboard,
                          color: Colors.white,
                          size: 20,
                        ),
                      ),
                      onTap: () {
                        controller.showEmojiPanel.value = !controller.showEmojiPanel.value;
                        if (!controller.showEmojiPanel.value) {
                          controller.focusNode.requestFocus();
                        } else {
                          controller.focusNode.unfocus();
                        }
                      },
                    ),
                    Spacer(),
                    GestureDetector(
                      onTap: controller.onSubmitComment,
                      child: Container(
                        margin: EdgeInsets.only(right: 15),
                        padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                        decoration: BoxDecoration(
                          color: controller.sendBtnEnabled.value ? Constants.themeColor : Colors.transparent,
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(color: controller.sendBtnEnabled.value ? Colors.transparent : Color(0xFF505050)),
                        ),
                        child: Text(
                          "发送",
                          style: TextStyle(color: controller.sendBtnEnabled.value ? Colors.white : Color(0xFF505050)),
                        ),
                      ),
                    )
                  ],
                ),
                SizedBox(
                  height: 10,
                ),
                AnimatedCrossFade(
                  sizeCurve: Curves.easeInOut,
                  firstChild: SizedBox(
                    height: controller.keyboardHeight,
                  ),
                  secondChild: _buildEmojiPanel(),
                  crossFadeState: controller.showEmojiPanel.value ? CrossFadeState.showSecond : CrossFadeState.showFirst,
                  duration: Duration(milliseconds: 250),
                ),
              ],
            ),
          );
        })
      ]),
    );
  }
}
